let ImportService = require('./ImportService')
let Mongodb = require('../../database/mongodb');

class TestCaseService extends ImportService{
  initParam () {
    this.tableConfigs = [
      { tableName: 'users' }
    ]
    this.enumTypes = ['SCREEN_TYPE']
  }

  formateData (dataList, { setId }) {
    return new Promise((resolve, reject) => {
      let rowDatas = []
      let data = {}
      // 1.数据转换
      for (let i = 0, len = dataList.length; i < len; i++) {
        data = dataList[i]
        rowDatas.push({
          "id": data[0],
          "name": data[1],
          "price": data[2],
          "ownerUser": this.dataFormater('users', data[3], 'email', 'userName'),
          "bugTime": data[4],
          "type": data[5],
          "version": data[6],
          "andriodVersion": data[7],
          "resolution": data[8],
          "size": data[9],
          "screenType": this.dataFormater('SCREEN_TYPE', data[10]),
          "note": data[11],
          "orgId": this.user.orgId[0],
          "createDate": new Date(),
          "createUser": this.user.email
        })        
      }
      resolve(rowDatas)
    })
  }

  saveData (tableName, docs) {
    return new Promise((resolve, reject) => {
      let ids = new Set()
      for (let index = 0; index < docs.length; index++) {
        const element = docs[index];
        if (element.id) {
          ids.add(element.id)
        }
      }
      let condition = {
        id: { '$in': Array.from(ids) }
      }
      if (ids.size > 0) {
        Mongodb.find('phone', condition, null, null, (err, hasDataList) => {
          let idMap = new Map()
          for (let index = 0; index < hasDataList.length; index++) {
            const element = hasDataList[index];
            idMap.set(element.id, element._id)
          }
          for (let index = 0; index < docs.length; index++) {
            const element = docs[index];
            if (element.id && idMap.has(element.id)) {
              Mongodb.update(tableName, { _id: idMap.get(element.id) }, element, (err, docs) => {});
            } else {
              Mongodb.save(tableName, element, (err, docs) => {});
            }
          }
        })
      } else {
        Mongodb.saveDocs(tableName, docs, (err, docs) => {
          if (err) {
            reject(err);
          } else {
            resolve(docs);
          }
        });
      }
    });
  }
}

module.exports = new TestCaseService()